<!--
  企业用户管理-管理员设置
 -->
<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="名称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="dept">
        <el-input
          v-model="queryParams.dept"
          placeholder="请输入部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职位" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入职位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model.number="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
        >搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>
    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="序号" type="index" />
      <el-table-column label="姓名" align="center" prop="nickname" />
      <!-- todo 分析学校 -->
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="职位" align="center" prop="remark" />
      <el-table-column label="手机号" align="center" prop="mobile">
        <template slot-scope="scope">
          <span>{{ scope.row.mobile | decodeMobileWithSecret }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号开通时间" align="center" prop="createTime" />
      <el-table-column label="最近登录时间" align="center" prop="loginDate" />
      <el-table-column
        label="操作"
        align="center"
        class-nickname="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            style="margin-right: 10px"
            @click="handleMenuEdit(scope.row)"
          >菜单权限配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            style="margin-right: 10px"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-popconfirm
            title="确认删除吗？"
            @confirm="handleDelete(scope.row)"
          >
            <el-button slot="reference" size="mini" type="text">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :title="`${isEdit ? '编辑' : '新建'}员工账号`"
      :visible.sync="openDialog"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="nickname">
          <el-input v-model="addForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" />
        </el-form-item>
        <el-form-item label="部门" prop="deptName">
          <el-input v-model="addForm.deptName" />
        </el-form-item>
        <el-form-item label="职位" prop="remark">
          <el-input v-model="addForm.remark" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 菜单权限配置 -->
    <el-dialog
      title="菜单权限配置"
      :visible.sync="openMenuDialog"
      width="500px"
      append-to-body
    >
      <el-form ref="menuForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜单权限">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event)"
          >展开/折叠</el-checkbox>
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event)"
          >全选/全不选</el-checkbox>
          <el-tree
            ref="menu"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            :check-strictly="menuCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompanyUser,
  createCompanyUser,
  deleteCompanyUser,
  updateCompanySonUser,
  assignUserMenu,
  getListUserResources
} from '@/api/company-admin-api/userManage/index.js'
import { getUserCountByMobile } from '@/api/company-admin-api/userManage/index.js'
import { listSimpleMenus } from '@/api/system/menu'
import { attentionEvent, inviteWay } from '@/utils/frontDataDict.js'
import moment from 'moment'
import { deepClone } from '../../../utils'
import {
  decodeMobile,
  encryptDesMobile
} from '../../../directive/mobileDecode'

export default {
  nickname: 'Company',
  components: {},
  data() {
    const validataEmail = (rule, value, callback) => {
      const emailReg =
        /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
      if (value === '') {
        return callback(new Error('邮箱不可为空'))
      } else {
        if (emailReg.test(value)) {
          return callback()
        } else {
          return callback(new Error('格式有误'))
        }
      }
    }
    return {
      menuOptions: [],
      inviteWay: inviteWay,
      attentionEvent: attentionEvent,
      ResumeReviewDialog: false,
      currentResume: null, // 当前要邀请的简历
      list: [],
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        dept: '',
        nickname: '',
        mobile: '',
        remark: '',
        pageNo: 1,
        pageSize: 10
      },
      currentItem: null,
      // 条件
      conditionDialog: false,
      isReview: false,
      jobInfo: {},
      inviteForm: {},
      openDialog: false,
      addForm: {
        id: '',
        username: '', // 用户账号 必填，这里用手机号,不展示在表单内
        nickname: '', // 用户名
        mobile: '', // 手机号
        email: '', // 邮箱
        deptName: '', // 部门
        remark: '' // 职位
      },
      rules: {
        nickname: [
          { required: true, message: '请填写您的真实姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: validataEmail,
            message: '请填写邮箱地址',
            trigger: 'blur'
          }
        ],
        deptName: [
          { required: true, message: '请填写您所在部门', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请填写您的职位', trigger: 'blur' }
        ],
        menuIds: [
          {
            required: true,
            message: '关联的菜单编号不能为空',
            trigger: 'blur'
          }
        ]
      },
      isEdit: false,
      captchaEnable: true,
      openMenuDialog: false,
      menuCheckStrictly: true,
      menuNodeAll: false,
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      menuExpand: false,
      form: {},
      /**
       * 每个企业用户必须有的基础菜单，保证可以登录使用
       * 1381 统计看板（企业）
       * 1382 平台概览
       */
      requireMenu: [],
      allKey: []
    }
  },
  created() {
    this.getList()
    this.getMenus()
  },
  methods: {
    cancel() {
      this.openMenuDialog = false
    },
    /** 获得菜单 */
    getMenus() {
      listSimpleMenus().then((response) => {
        this.allKey = response.data.map((item) => {
          if (item.name === '统计看板（企业）' || item.name === '平台概览') {
            this.requireMenu.push(item.id)
          }
          return item.id
        })
        // 处理 menuOptions 参数
        this.menuOptions = []
        // 只需要配置
        this.menuOptions.push(
          ...this.handleTree(
            response.data.filter((item) => {
              return item.name !== '管理员设置'
            }),
            'id'
          )
        )
        this.menuOptions.map((item) => {
          if (this.requireMenu.includes(item.id)) {
            item.disabled = true
          }
          item.children.map((row2) => {
            if (this.requireMenu.includes(row2.id)) {
              row2.disabled = true
            }
          })
        })
      })
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      const treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      if (value) {
        this.$refs.menu.setCheckedKeys(this.allKey)
      } else {
        this.$refs.menu.setCheckedKeys([])
        this.requireMenu.map((item) => {
          this.$refs.menu.setChecked(item, true, false)
        })
      }
    },
    /** 提交企业用户菜单配置 */
    submitForm() {
      this.$refs['menuForm'].validate((valid) => {
        if (!valid) {
          return
        }
        const result = [
          ...this.$refs.menu.getCheckedKeys(),
          ...this.$refs.menu.getHalfCheckedKeys()
        ]
        assignUserMenu({
          menuIds: result,
          userId: this.currentItem.id
        }).then((res) => {
          if (res && res.code === 0) {
            this.$message.success('操作成功')
            this.openMenuDialog = false
          }
        })
      })
    },
    // 提交企业用户表单
    submitAddForm() {
      this.$refs.addForm.validate((boo) => {
        if (boo) {
          getUserCountByMobile({ mobile: this.addForm.mobile }).then((res) => {
            if (!this.isEdit && res && res.data > 0) {
              this.$message.warning(
                '该手机号已存在企业用户，请更换手机号后重试'
              )
            } else {
              const { nickname, mobile, remark, deptName, email, code, id } =
                this.addForm
              const param = {
                nickname,
                password: mobile, // 密码 默认是手机号，全用短信登录，密码废弃，但还要传
                username: mobile, // 用户账号
                mobile: mobile,
                remark, // 职位
                deptName,
                email,
                code,
                id
              }
              if (this.isEdit) {
                param.mobile = encryptDesMobile(param.mobile)
              }
              const handle = this.isEdit
                ? updateCompanySonUser
                : createCompanyUser
              handle(param).then((res) => {
                if (res.code === 0 && res.data) {
                  this.openDialog = false
                  this.addForm = this.$options.data().addForm
                  this.$message.success(`${this.isEdit ? '编辑' : '创建'}成功`)
                  this.getList()
                }
              })
            }
          })
        }
      })
    },
    handleMenuEdit(item) {
      this.currentItem = item
      getListUserResources(item.id).then((res) => {
        if (res && res.code === 0) {
          this.menuCheckStrictly = true
          this.openMenuDialog = true
          this.menuCheckStrictly = false
          this.menuExpand = false
          this.menuNodeAll = false
          this.$nextTick(() => {
            // 菜单选择重置
            if (this.$refs.menu) {
              if (res.data.length) {
                this.requireMenu.map((j) => {
                  if (!res.data.includes(j)) {
                    res.data.push(j)
                  }
                })
                // this.$refs.menu.setCheckedKeys(res.data)
                res.data.map((id) => {
                  this.$refs.menu.setChecked(id, true, false)
                })
              } else {
                this.requireMenu.map((id) => {
                  this.$refs.menu.setChecked(id, true, false)
                })
              }
            }
          })
        }
      })
    },
    handleEdit(item) {
      const param = {
        id: item.id,
        username: decodeMobile(item.mobile) || '', // 用户账号 必填，这里用手机号,不展示在表单内
        nickname: item.nickname || '', // 用户名
        mobile: decodeMobile(item.mobile) || '', // 手机号
        email: item.email || '', // 邮箱
        deptName: item.deptName || '', // 部门
        remark: item.remark || '' // 职位
      }
      Object.assign(this.addForm, param)
      this.isEdit = true
      this.openDialog = true
    },
    handleClose() {
      Object.keys(this.addForm).map((key) => (this.addForm[key] = ''))
      this.openDialog = false
    },
    handleAdd() {
      this.addForm = this.$options.data().addForm
      this.isEdit = false
      this.openDialog = true
    },
    handleDelete(item) {
      deleteCompanyUser({ id: item.id }).then((res) => {
        if (res.code === 0 && res.data) {
          this.$message.success('删除成功')
          this.getList()
        }
      })
    },
    /** 查询列表 */
    getList(newParams = null) {
      this.loading = true
      // 处理查询参数
      const params = deepClone(this.queryParams)
      if (newParams) {
        Object.assign(params, newParams)
      }
      for (const key in params) {
        if (params[key] === null || params[key] === '') {
          delete params[key]
        }
      }
      // 执行查询
      getCompanyUser(params).then((response) => {
        const companyLoginPhone = localStorage.getItem('companyLoginPhone')
        this.list = response.data.list.map((item) => {
          item.createTime = item.createTime
            ? moment(item.createTime).format('yyyy-MM-DD HH:MM:SS')
            : item.createTime
          item.loginDate = item.loginDate
            ? moment(item.loginDate).format('yyyy-MM-DD HH:MM:SS')
            : item.loginDate
          item.dept = item.dept || '--'
          // 系统遗留问题，职位字段用remark代替
          item.remark = item.remark || '--'
          item.isAdmin = companyLoginPhone === item.mobile
          return item
        })
        this.total = response.data.total
        this.loading = false
        this.conditionDialog = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = []
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
<style lang="scss" scope>
.left-item {
  position: relative;
  width: calc(100vw * 520 / 1920);
  min-width: 300px;
  border-radius: 9px;
  background: url("../../../assets/images/user/deliver-bg.png") no-repeat top
    center / cover;
  padding: 40px 25px 25px;
  border: 1px solid #d4d6da;
  cursor: pointer;
  overflow: hidden;

  &:nth-child(3n) {
    margin: 30px 0px 0px 0;
  }

  .title {
    font-size: 32px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #37383d;
    line-height: 45px;
    margin-bottom: 22px;

    > span {
      font-size: 22px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #9597a0;
      line-height: 30px;
      margin-left: 15px;
    }
  }

  .row {
    line-height: 30px;
    margin-bottom: 23px;

    .local-icon {
      display: inline-block;
      width: 20px;
      height: 24px;
      background: url("../../../assets/images/user/local.png") no-repeat center
        center / cover;
      margin-right: 12px;
    }

    .city {
      font-size: 22px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #37383d;
      line-height: 30px;
      margin-right: 25px;
    }

    .small-text {
      font-size: 22px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #9597a0;
      line-height: 30px;
    }

    .line {
      display: inline-block;
      width: 1px;
      height: 14px;
      background: #9597a0;
      margin: 0 20px;
    }
  }

  .row2 {
    font-size: 22px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #9597a0;
    line-height: 30px;
    margin-bottom: 35px;

    .line {
      display: inline-block;
      width: 1px;
      height: 14px;
      background: #9597a0;
      margin: 0 20px;
    }
  }

  .date {
    line-height: 30px;
    font-size: 20px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #c4c4c4;
    text-align: right;

    .open {
      float: left;
      font-size: 22px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #2f8efe;
      line-height: 30px;
    }
  }

  .feedback-tips {
    position: absolute;
    right: 10%;
    bottom: 30%;
    border-radius: 4px;
    border: 1px solid #6fc70f;
    font-size: 26px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #6fc70f;
    line-height: 37px;
    padding: 0 18px;
    transform: rotateZ(-35deg);
  }
}

.right-detail {
  position: relative;
  width: calc(100vw * 920 / 1920);
  min-width: 520px;
  background-color: #fff;

  .right-detailhead {
    position: relative;
    border-bottom: 1px solid #d4d6da;
    line-height: 85px;
    font-size: 30px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #37383d;
    padding-left: 25px;

    .close-icon {
      position: absolute;
      width: 22px;
      height: 22px;
      right: 34px;
      top: 50%;
      margin-top: -11px;
      line-height: 22px;
      color: #b0b0b0;
      font-size: 22px;
      text-align: center;
      cursor: pointer;
    }
  }

  .right-detail-content {
    position: relative;
    width: 100%;
    padding: 38px 45px 60px;

    .title {
      font-size: 24px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      margin-bottom: 25px;
    }

    .row {
      position: relative;
      width: 100%;
      display: flex;
      flex-flow: row nowrap;
      margin-bottom: 25px;

      .left {
        width: 112px;
        font-size: 26px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #37383d;
        line-height: 37px;
        text-align: left;
        margin-right: 40px;
      }

      .reject-reason {
        width: 100%;
        font-size: 26px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #37383d;
        line-height: 37px;
        text-align: left;
        margin-right: 40px;

        span {
          font-size: 20px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #c4c4c4;
          line-height: 28px;
        }
      }

      .right {
        flex: 1;
        overflow: hidden;
        line-height: 37px;

        .text {
          font-size: 26px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #37383d;
          line-height: 37px;
        }

        .address {
          font-size: 26px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #37383d;
          line-height: 37px;
          .position-icon {
            position: relative;
            display: inline-block;
            top: 4px;
            width: 24px;
            height: 29px;
            margin-right: 15px;
            background: url("../../../assets/images/position.png") no-repeat
              center center / cover;
            // vertical-align: middle;
          }
        }
      }
    }

    .btn-box {
      position: relative;
      margin-top: 50px;
      width: 100%;
      display: flex;
      flex-flow: row nowrap;
      justify-content: center;
      align-items: center;

      .btn {
        line-height: calc(100vw * 68 / 1920);
        height: calc(100vw * 68 / 1920);
        border-radius: 4px;
        border: 1px solid #4677b9;
        text-align: center;
        padding: 0 calc(100vw * 65 / 1920);
        font-size: calc(100vw * 24 / 1920);
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #4677b9;
        margin: 0 calc(100vw * 25 / 1920);
        cursor: pointer;
      }

      .confirm {
        background-color: #4677b9;
        color: #fff;
      }
    }

    .feedback-tips {
      position: absolute;
      right: 45px;
      top: 20%;
      border-radius: 4px;
      border: 2px solid #6fc70f;
      font-size: 26px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #6fc70f;
      line-height: 50px;
      padding: 0 18px;
      transform: rotateZ(-35deg);
      z-index: 1;
    }

    .reject-tips {
      position: absolute;
      right: 45px;
      top: 20%;
      border-radius: 4px;
      border: 2px solid rgb(180, 52, 29);
      font-size: 26px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: rgb(180, 52, 29);
      line-height: 50px;
      padding: 0 18px;
      transform: rotateZ(-35deg);
      z-index: 1;
    }

    .feedback-confirm-tips {
      position: absolute;
      right: 45px;
      bottom: 20%;
      border-radius: 4px;
      border: 2px solid #6fc70f;
      font-size: 26px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #6fc70f;
      line-height: 50px;
      padding: 0 18px;
      transform: rotateZ(-35deg);
      z-index: 1;
    }

    .success-icon {
      display: block;
      width: 160px;
      height: 160px;
      margin: 50px auto 20px;
    }

    .succes-tips {
      font-size: 26px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #37383d;
      line-height: 37px;
      margin-bottom: 34px;
      text-align: center;
    }

    .safe-icon {
      font-size: 22px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #fc9c21;
      line-height: 30px;
      text-align: center;
      margin-bottom: 14px;
    }

    .safe-tips {
      font-size: 18px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #c4c4c4;
      line-height: 25px;
    }
  }
}
.login-code-img {
  height: 38px;
}
</style>
